package com.ming.liteflow.core.el;

import com.ming.liteflow.core.graph.GraphEL;
import com.ming.liteflow.core.graph.LogicFlowData;
import com.ming.liteflow.core.graph.Node;
import com.ming.liteflow.core.json.ELJsonUtil;
import com.ming.liteflow.core.node.NodeInfo;
import com.ming.liteflow.execption.LiteFlowELException;
import com.yomahub.liteflow.builder.el.ELBus;
import com.yomahub.liteflow.builder.el.ELWrapper;
import com.yomahub.liteflow.builder.el.WhenELWrapper;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Flow {

    private GraphEL graphEL;
    private boolean formatEL = false;
    private ELWrapper wrapper;
    private Map<Long,NodeInfo> nodeInfoMap;

    public static Flow NEW(){
        return new Flow();
    }

    public Flow nodeInfoList(List<NodeInfo> list) {
        this.nodeInfoMap = list.stream().collect(Collectors.toMap(m->m.getId(),m->m));
        return this;
    }

    public Flow logicFlow(String json) throws LiteFlowELException {
        List<LogicFlowData> flowDataList = ELJsonUtil.getLogicFlowGroup(json);
        if(flowDataList.size() > 1){
            //多起点嵌套处理
            WhenELWrapper when = ELBus.when();
            for (LogicFlowData data : flowDataList){
                GraphEL graph = GraphEL.getGraphEL(data);
                graph.setNodeInfoMap(nodeInfoMap);
                when.when(FlowConvertEL.logicFlow(graph));
                graph.setGroupNodeProp(graph.getStartNode(), when);//设置分组属性
            }
            this.wrapper = when;
        }else if(flowDataList.size() == 1){
            //单起点嵌套处理
            this.graphEL = GraphEL.getGraphEL(flowDataList.get(0));
            this.graphEL.setNodeInfoMap(nodeInfoMap);
            this.wrapper = FlowConvertEL.logicFlow(graphEL);
        }
        return this;
    }

    public Flow formatEL(){
        this.formatEL = true;
        return this;
    }

    public String buildEL(){
        return wrapper.toEL(formatEL);
    }

    public String buildEL(boolean formatEL){
        return wrapper.toEL(formatEL);
    }

    public String exec(){ return null; }

    public static void main(String[] args) {
        //System.out.println(Flow.NEW().logicFlow(ELJson.when_json_1).buildEL());
        //System.out.println(Flow.NEW().logicFlow(ELJson.then_json_1).buildEL());
        //System.out.println(Flow.NEW().logicFlow(ELJson.bx_json_1).formatEL().buildEL());
        //System.out.println(Flow.NEW().logicFlow(ELJson.bx_json_2).formatEL().buildEL());
        //System.out.println(Flow.NEW().logicFlow(ELJson.bx_json_4).formatEL().buildEL());
    }


}
